package com.xmhmyh.generalframework.common.utils.sms;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.xmhmyh.generalframework.common.utils.sms.model.request.SmsSendRequest;
import com.xmhmyh.generalframework.common.utils.sms.model.response.SmsSendResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

/**
 * @author yuding
 */
@Slf4j
@Component
public class SmsSendUtil {
    @Value("${sms.account}")
    private String account;
    @Value("${sms.password}")
    private String password;
    @Value("${smsTemplate.verificationCodeTemplate}")
    private String VERIFICATIONCODE_TEMPLATE;
    private String smsSingleRequestServerUrl = "http://smssh1.253.com/msg/send/json";
    private String sign = "【华美云海】";


    /**
     * @Author: 于丁
     * @Description: 发送验证码
     * @DateTime: 2020/3/9 4:25 下午
     * @Params:
     * @Return
     */
    public int sendVerificationCode(String code, String phone) {
        return senSms(phone, sign + MessageFormat.format(VERIFICATIONCODE_TEMPLATE, code));
    }

    /**
     * @Author: 于丁
     * @Description: 短信发送
     * @DateTime: 2020/3/9 4:27 下午
     * @Params:
     * @Return
     */
    private int senSms(String phone, String msg) {
        //状态报告
        String report = "true";
        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, password, msg, phone, report);
        String requestJson = JSON.toJSONString(smsSingleRequest);
        log.info("before request string is: " + requestJson);
        String response = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, requestJson);
        log.info("response after request result is :" + response);
        SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);
        return Convert.toInt(smsSingleResponse.getCode(), 1);
    }
}
